package com.example.cachedemo.service;

import com.example.cachedemo.entity.Comment;
import com.example.cachedemo.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;
    //查询方法
    @Cacheable(cacheNames = "comment")
    public Comment findById(int comment_id){
        Optional<Comment> byId = commentRepository.findById(comment_id);
        if(byId.isPresent()){
            return byId.get();
        }
        else{
            return null;
        }
    }

    //更新方法
    @CachePut(value = "comment",key = "#result.id")
    public Comment updateComment(Comment comment){
        int updateComment = commentRepository.updateComment(comment.getAuthor(),comment.getId() );
        return comment;
    }

    //删除方法
    @CacheEvict(value = "comment",key="#comment_id")
    public void deleteComment(int comment_id){
        commentRepository.deleteById(comment_id);
    }

}
